<?php

namespace Common\Controller;

use Think\Controller;

/**
 *   所有模块控制器下基类
 */
class BaseController extends Controller {

    public $backendTaskType = array(
        'ADD' => 0,
        'EDIT' => 1,
        'CANCEL' => 2
    );
    private $backendQueueClient = null;
    private $backendQueueConnected = false;
    private static $http = array(
        100 => "HTTP/1.1 100 Continue",
    );

    /**
     * baseController静态属性,标记是否处于事务嵌套状态
     * @var boolean
     */
    private static $_multiTransMode = false;
    protected function setMultiTransMode($status = null) {
        $this->_multiTransMode = empty($status) ? false : true;
    }
    protected function getMultiTransMode() {
        return $this->_multiTransMode;
    }

    protected function _initialize() {
        
    }

    /**
     * 逻辑业务层获取相关方法的缓存
     * @param  mixin $method 调用方法
     * @param  array  $vars   参数
     * @return mixin 方法返回
     */
    protected function __singleGet($method, $vars = array()) {
        static $__singleThreadData = array();
        $dataKey = hash_array(array($method, $vars));
        if (isset($__singleThreadData[$dataKey]))
            return $__singleThreadData[$dataKey];

        $data = call_user_func_array(array(&$this, $method), $vars);
        $__singleThreadData[$dataKey] = $data;
        return $data;
    }

    /**
     * 成功页面跳转
     */
    protected function successTips($message = '', $jumpUrl = '', $ajax = false) {
        if (true === $ajax || IS_AJAX) {

            // AJAX提交
            $data = is_array($ajax) ? $ajax : array();
            $data['info'] = $message;
            $data['url'] = $jumpUrl;
            $this->ajaxReturn($data);
        }
        if (is_int($ajax))
            $this->assign('waitSecond', $ajax);
        if (!empty($jumpUrl))
            $this->assign('jumpUrl', $jumpUrl);

        // 提示标题
        $this->assign('msgTitle', $status ? L('_OPERATION_SUCCESS_') : L('_OPERATION_FAIL_'));

        //如果设置了关闭窗口，则提示完毕后自动关闭窗口
        if ($this->get('closeWin'))
            $this->assign('jumpUrl', 'javascript:window.close();');

        //保证输出不受静态缓存影响
        C('HTML_CACHE_ON', false);

        $this->assign('message', $message);

        // 提示信息
        // 成功操作后默认停留1秒
        if (!isset($this->waitSecond))
            $this->assign('waitSecond', '1');

        // 默认操作成功自动返回操作前页面
        if (!isset($this->jumpUrl))
            $this->assign("jumpUrl", $_SERVER["HTTP_REFERER"]);
        $this->display(C('TMPL_ACTION_SUCCESS'));
        exit;
    }

    /**
     * 信息页面跳转提示
     * @param type $message
     * @param type $jumpUrl
     * @param type $ajax
     */
    protected function messageTips($message = '', $jumpUrl = '', $ajax = false, $waitSecond) {
        if (true === $ajax || IS_AJAX) {
            $data = is_array($ajax) ? $ajax : array();
            $data['info'] = $message;
            $data['url'] = $jumpUrl;
            $this->ajaxReturn($data);
        }

        //保证输出不受静态缓存影响
        C('HTML_CACHE_ON', false);

        $this->assign('message', $message);

        // 提示信息
        // 成功操作后默认停留1秒
        if (!isset($waitSecond))
            $this->assign('waitSecond', '1');

        // 默认操作成功自动返回操作前页面
        if (!isset($jumpUrl))
            $this->assign("jumpUrl", $_SERVER["HTTP_REFERER"]);
        $this->display(C('TMPL_ACTION_MESSAGE'));
        exit;
    }

    /**
     * 错误页面跳转
     */
    protected function errorTips($message = '', $jumpUrl = '', $ajax = false, $waitSecond) {
        if (true === $ajax || IS_AJAX) {

            // AJAX提交
            $data = is_array($ajax) ? $ajax : array();
            $data['info'] = $message;
            $data['status'] = $status;
            $data['url'] = $jumpUrl;
            $this->ajaxReturn($data);
        }

        //  echo 'fffffffffffff'; exit;
        if (is_int($ajax))
            $this->assign('waitSecond', $ajax);
        if (!empty($jumpUrl))
            $this->assign('jumpUrl', $jumpUrl);

        // 提示标题
        $this->assign('msgTitle', $status ? L('_OPERATION_SUCCESS_') : L('_OPERATION_FAIL_'));

        //如果设置了关闭窗口，则提示完毕后自动关闭窗口
        if ($this->get('closeWin'))
            $this->assign('jumpUrl', 'javascript:window.close();');
        $this->assign('status', $status);

        // 状态
        //保证输出不受静态缓存影响
        C('HTML_CACHE_ON', false);

        $this->assign('error', $message);

        // 提示信息
        //发生错误时候默认停留3秒
        if (!isset($waitSecond))
            $this->assign('waitSecond', '3');

        // 默认发生错误的话自动返回上页
        if (!isset($jumpUrl))
            $this->assign('jumpUrl', "javascript:history.back(-1);");
        $this->display(C('TMPL_ACTION_ERROR'));

        // 中止执行  避免出错后继续执行
        exit;
    }

    /**
     * 封装返回函数，减少接口层代码量
     * @param  Object $validateUtil   new \Org\Util\Validate();
     * @param  mixin $value         待检测参数
     * @param  string $rule         检测规则Tag
     * @param  array $ruleNeeded 查看\Org\Util\Validate.class.php
     */
    protected function ajaxValidateReturn($validateUtil, $value, $rule, $ruleNeeded = null) {
        $isValid = $validateUtil->validate($value, $rule, $ruleNeeded);
        if (!$isValid) {
            $msg = $validateUtil->getError('explode', ',') ['msg'];
            returnJson($msg[0], $msg[1], $msg[2]);
            return false;
        }
        return true;
    }

    /**
     * AJAX请求检查验证码
     * @modify trainyao 2015-09-30 创建
     */
    protected function ajaxCheckVcode($vcode) {
        if (!checkVcode($vcode)) {
            returnJson(403, 122, 'error');
        }
    }

    /**
     * 
     * 发送请求到后台进行发送短信，获取房卡通知
     * @modify songanwei 2016-01-28
     * @param integer $type 操作类型
     * @params integer $hotelId 客栈ID
     * @param array $beforeInfoArray 变化前数据 [{mobile, roomName, orderRoomId}, {}, ..]
     * @param array $afterInfoArray 变化后数据 [{startdate(算上提前入住时间), enddate(算上提前入住时间), mobile, roomName(房间名), sendMessage(是否发送短信), orderRoomId}, {}, ..]
     */
    protected function pushBackendCardTask($type, $hotelId, $beforeInfoArray, $afterInfoArray, $isBooking = false) {
		$fileLog = new \Org\Util\FileLog();
        // 定义数据类型格式
        $data = array(
            'flag' => 'smsCard',
            'type' => $type,
            'hotelId' => $hotelId,
            'old' => empty($beforeInfoArray)?'[]':json_encode($beforeInfoArray),
            'new' => empty($afterInfoArray)?'[]':json_encode($afterInfoArray),
            'IsBooking' => $isBooking,
            'time' => time()
        );

        $fileLog->write(json_encode($data), 0, RUNTIME_PATH . "/Statistics/" . date('Y-m-d') . "_pushTask.log");
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'http://' . C('TASK_SERVER_IP') . ':' . C('TASK_SERVER_PORT'));
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);

        if ($result != 'success') {
            $fileLog->write('push failed!', 0, RUNTIME_PATH . "/Statistics/" . date('Y-m-d') . "_pushTask.log");
            return false;
        }
        return true;
    }
}
